package com.ccf.business.source.listener;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.ProgressListener;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 * 描述：
 * 文件上传监听
 * @author xianggj
 * @Date 2022/2/16 16:28
 **/
@Slf4j
public class FileUploadProgressListener  implements ProgressListener {

    public static final String FILE_KEY = "file_key";

    private HttpSession session;

    private String fileName;

    /**
     * 打印太快了 压缩打印
     */
    private long yBytesRead = 0;


    public FileUploadProgressListener(HttpSession session, String fileName) {
        this.session = session;
        if (StrUtil.isBlank(fileName)){
            fileName = "未知文件";
        }
        this.fileName = fileName;
        if (MultipartListenerResolver.FILE_PROGRESS_MAP.containsKey(fileName)){
            this.fileName = fileName+"(1)";
        }
        MultipartListenerResolver.FILE_PROGRESS_MAP.put(this.fileName, 0.0);
    }

    /**
     * 上传进度追踪 (单文件上传才能跟踪)
     * @param pBytesRead 已经上传的大小
     * @param pContentLength 文件总大小
     * @param pItems 文件块
     */
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
        long l = pBytesRead - yBytesRead;
        //传1M 打印一次
        if (l >= 1024000 ) {
            double rates = (Double.parseDouble(String.valueOf(pBytesRead))*100/pContentLength);
            BigDecimal b = new BigDecimal(rates, MathContext.UNLIMITED);
            double f1 = b.setScale(2, RoundingMode.UP).doubleValue();
            MultipartListenerResolver.FILE_PROGRESS_MAP.put(fileName, f1);
            log.info(this.fileName+"已经上传的大小:"+pBytesRead +";文件总大小:"+ pContentLength+";文件块："+pItems+";进度："+f1);
            yBytesRead = pBytesRead;
        }
    }

}
